<template>
  <div class="page-container">
    <h2>视频课程管理</h2>
    
    <!-- 搜索表单 -->
    <el-form :model="searchForm" inline class="search-form">
      <el-form-item label="视频信息">
        <el-input v-model="searchForm.videoInfo" placeholder="请输入视频信息" clearable />
      </el-form-item>
      <el-form-item label="价格范围">
        <el-input-number v-model="searchForm.minPrice" :min="0" placeholder="最低价格" />
        <span style="margin: 0 10px">-</span>
        <el-input-number v-model="searchForm.maxPrice" :min="0" placeholder="最高价格" />
      </el-form-item>
      <el-form-item label="视频类型">
        <el-select v-model="searchForm.videoType" placeholder="请选择视频类型" clearable>
          <el-option label="代码教学视频" :value="1" />
          <el-option label="剪辑视频" :value="2" />
          <el-option label="短视频拼接视频" :value="3" />
          <el-option label="舞蹈教学视频" :value="4" />
        </el-select>
      </el-form-item>
      <el-form-item label="视频状态">
        <el-select v-model="searchForm.videoState" placeholder="请选择视频状态" clearable>
          <el-option label="上架" :value="1" />
          <el-option label="下架" :value="0" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">
          <el-icon><Search /></el-icon>
          搜索
        </el-button>
        <el-button @click="handleReset">
          <el-icon><Refresh /></el-icon>
          重置
        </el-button>
        <el-button type="success" @click="handleAdd">
          <el-icon><Plus /></el-icon>
          新增视频
        </el-button>
      </el-form-item>
    </el-form>

    <!-- 数据表格 -->
    <el-table 
      :data="displayedData" 
      v-loading="loading"
      class="table-container"
      border
      stripe
    >
      <template #empty>
        <div style="padding: 24px; color: #909399;">暂无数据</div>
      </template>
      <el-table-column prop="videoId" label="视频ID" width="80" />
      <el-table-column prop="videoInfo" label="视频信息" min-width="200" />
      <el-table-column prop="videoPrice" label="视频价格" width="120">
        <template #default="{ row }">
          <span style="color: #f56c6c; font-weight: bold;">
            ¥{{ row.videoPrice?.toFixed(2) || '0.00' }}
          </span>
        </template>
      </el-table-column>
      <el-table-column prop="subscribeNum" label="订阅数" width="100">
        <template #default="{ row }">
          <el-tag type="info">{{ row.subscribeNum || 0 }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="videoType" label="视频类型" width="120">
        <template #default="{ row }">
          <el-tag :type="getVideoTypeTagType(row.videoType)">
            {{ getVideoTypeText(row.videoType) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="videoState" label="视频状态" width="100">
        <template #default="{ row }">
          <el-tag :type="row.videoState === 1 ? 'success' : 'danger'">
            {{ row.videoState === 1 ? '上架' : '下架' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="180">
        <template #default="{ row }">
          {{ formatDate(row.createTime) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="{ row }">
          <el-button type="primary" size="small" @click="handleEdit(row)">
            <el-icon><Edit /></el-icon>
            编辑
          </el-button>
          <el-button type="danger" size="small" @click="handleDelete(row)">
            <el-icon><Delete /></el-icon>
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <div style="margin-top: 16px; text-align: right;">
      <el-pagination
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="pagination.total"
        :page-size="pagination.pageSize"
        :current-page="pagination.pageNum"
        :page-sizes="[5,10,20,50]"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 添加/编辑对话框 -->
    <el-dialog 
      v-model="dialogVisible" 
      :title="dialogTitle"
      width="600px"
      @close="handleDialogClose"
    >
      <el-form 
        ref="formRef"
        :model="formData" 
        :rules="formRules" 
        label-width="100px"
      >
        <el-form-item label="视频信息" prop="videoInfo">
          <el-input 
            v-model="formData.videoInfo" 
            type="textarea"
            :rows="3"
            placeholder="请输入视频详细信息" 
          />
        </el-form-item>
        <el-form-item label="视频价格" prop="videoPrice">
          <el-input-number 
            v-model="formData.videoPrice" 
            :min="0" 
            :precision="2"
            placeholder="请输入视频价格"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="订阅数" prop="subscribeNum">
          <el-input-number v-model="formData.subscribeNum" :min="0" />
        </el-form-item>
        <el-form-item label="视频类型" prop="videoType">
          <el-select v-model="formData.videoType" placeholder="请选择视频类型">
            <el-option label="教学视频" :value="1" />
            <el-option label="娱乐视频" :value="2" />
            <el-option label="直播回放" :value="3" />
            <el-option label="其他" :value="4" />
          </el-select>
        </el-form-item>
        <el-form-item label="视频状态" prop="videoState">
          <el-radio-group v-model="formData.videoState">
            <el-radio :label="1">上架</el-radio>
            <el-radio :label="0">下架</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, Plus, Edit, Delete } from '@element-plus/icons-vue'
import { videoApi } from '@/api/video'
import dayjs from 'dayjs'

// 响应式数据
const loading = ref(false)
const submitLoading = ref(false)
const dialogVisible = ref(false)
const dialogTitle = ref('')
const formRef = ref()
const router = useRouter()

// 搜索表单
const searchForm = reactive({
  videoInfo: '',
  minPrice: null,
  maxPrice: null,
  videoType: null,
  videoState: null
})

// 表格数据
const tableData = ref([])

// 分页
const pagination = reactive({
  pageNum: 1,
  pageSize: 10,
  total: 0
})

// 过滤后的数据
const filteredData = computed(() => {
  return (tableData.value || []).filter(item => {
    const matchInfo = !searchForm.videoInfo || (item.videoInfo || '').includes(searchForm.videoInfo)
    const matchType = (searchForm.videoType === null || searchForm.videoType === undefined) || item.videoType === searchForm.videoType
    const matchState = (searchForm.videoState === null || searchForm.videoState === undefined) || item.videoState === searchForm.videoState
    const matchMin = (searchForm.minPrice === null || searchForm.minPrice === undefined) || (Number(item.videoPrice) >= Number(searchForm.minPrice))
    const matchMax = (searchForm.maxPrice === null || searchForm.maxPrice === undefined) || (Number(item.videoPrice) <= Number(searchForm.maxPrice))
    return matchInfo && matchType && matchState && matchMin && matchMax
  })
})

// 当前页展示数据
const displayedData = computed(() => {
  pagination.total = filteredData.value.length
  const start = (pagination.pageNum - 1) * pagination.pageSize
  const end = start + pagination.pageSize
  return filteredData.value.slice(start, end)
})

// 表单数据
const formData = reactive({
  videoId: null,
  videoInfo: '',
  videoPrice: 0,
  subscribeNum: 0,
  videoType: 1,
  videoState: 1
})

// 表单验证规则
const formRules = {
  videoInfo: [
    { required: true, message: '请输入视频信息', trigger: 'blur' }
  ],
  videoPrice: [
    { required: true, message: '请输入视频价格', trigger: 'blur' },
    { type: 'number', min: 0, message: '价格不能小于0', trigger: 'blur' }
  ],
  videoType: [
    { required: true, message: '请选择视频类型', trigger: 'change' }
  ],
  videoState: [
    { required: true, message: '请选择视频状态', trigger: 'change' }
  ]
}

// 获取视频类型文本
const getVideoTypeText = (type) => {
  const typeMap = {
    1: '教学视频',
    2: '娱乐视频',
    3: '直播回放',
    4: '其他'
  }
  return typeMap[type] || '未知'
}

// 获取视频类型标签类型
const getVideoTypeTagType = (type) => {
  const typeMap = {
    1: 'success',
    2: 'warning',
    3: 'info',
    4: ''
  }
  return typeMap[type] || ''
}

// 格式化日期
const formatDate = (date) => {
  return date ? dayjs(date).format('YYYY-MM-DD HH:mm:ss') : '-'
}

// 获取视频列表
const getVideoList = async () => {
  try {
    loading.value = true
    const response = await videoApi.getVideoList(searchForm)
    tableData.value = response.data || []
  } catch (error) {
    ElMessage.error('获取视频列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.pageNum = 1
  getVideoList()
}

// 重置
const handleReset = () => {
  Object.assign(searchForm, {
    videoInfo: '',
    minPrice: null,
    maxPrice: null,
    videoType: null,
    videoState: null
  })
  getVideoList()
}

// 新增视频
const handleAdd = () => {
  dialogTitle.value = '新增视频'
  resetFormData()
  dialogVisible.value = true
}

// 新增入口移至侧边栏

// 编辑视频
const handleEdit = (row) => {
  dialogTitle.value = '编辑视频'
  Object.assign(formData, row)
  dialogVisible.value = true
}

// 删除视频
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除该视频吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await videoApi.deleteVideo(row.videoId)
    ElMessage.success('删除成功')
    getVideoList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 提交表单
const handleSubmit = async () => {
  try {
    await formRef.value.validate()
    submitLoading.value = true
    
    if (formData.videoId) {
      await videoApi.updateVideo(formData)
      ElMessage.success('修改成功')
    } else {
      await videoApi.addVideo(formData)
      ElMessage.success('添加成功')
    }
    
    dialogVisible.value = false
    getVideoList()
  } catch (error) {
    if (error !== false) {
      ElMessage.error(formData.videoId ? '修改失败' : '添加失败')
    }
  } finally {
    submitLoading.value = false
  }
}

// 重置表单数据
const resetFormData = () => {
  Object.assign(formData, {
    videoId: null,
    videoInfo: '',
    videoPrice: 0,
    subscribeNum: 0,
    videoType: 1,
    videoState: 1
  })
}

// 关闭对话框
const handleDialogClose = () => {
  formRef.value?.resetFields()
  resetFormData()
}

// 处理每页显示条数变化
const handleSizeChange = (size) => {
  pagination.pageSize = size
  pagination.pageNum = 1
}

// 处理当前页变化
const handleCurrentChange = (page) => {
  pagination.pageNum = page
}

// 初始化
onMounted(() => {
  getVideoList()
})
</script>

<style scoped>
.search-form {
  background-color: #f8f9fa;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
}

.table-container {
  margin-top: 20px;
}

.dialog-footer {
  text-align: right;
}
</style>
